package com.fas.hehe.system.controller;

import java.util.HashMap;
import java.util.List;

import com.fas.core.BaseController;
import com.fas.core.plugin.jfinal.route.ControllerBind;
import com.fas.core.plugin.treeview.TreeNode;
import com.fas.hehe.system.model.Organization;
import com.fas.hehe.system.service.OrganizationService;
@ControllerBind(controllerKey="/system/organization" , viewPath="/system/organization")
public class OrganizationController extends BaseController {

	public OrganizationService organizationService;
	
	//【异步】 加载组织机构树
	public void loadOrganizationTreeData(){
		boolean isSuccess = true;
		HashMap<String,Object> returnData = new HashMap<String,Object>();
		try{
			List<TreeNode> treeNodes = organizationService.loadTreeviewOnceTime();
			returnData.put("treeNodes", treeNodes);
		}catch(Exception e){
			isSuccess = false;
			log.error("初始化组织机构树异常", e);
		}
		this.returnJsonResult(isSuccess,returnData);
	}
	
	//【异步】 根据组织机构ID查询组织机构信息（包含基本、子机构列表）
	public void loadOrganizationInfoById(){
		boolean isSuccess = true;
		HashMap<String,Object> returnData = new HashMap<String,Object>();
		try{
			Organization org = organizationService.findOrganizationById(this.getParaToLong("orgId"));
			List<Organization> subOrgs = organizationService.findSubOrganizationById(this.getParaToLong("orgId"));
			returnData.put("org", org);
			returnData.put("subOrgs", subOrgs);
		}catch(Exception e){
			isSuccess = false;
			log.error("根据组织机构ID查询组织机构信息异常", e);
		}
		this.returnJsonResult(isSuccess,returnData);
	}
	
	//【异步】 修改组织机构显示顺序
	public void changeOrganizationPriority(){
		boolean isSuccess = true;
		try{
			Long parentId = this.getParaToLong("parentId");
			String type = this.getPara("type");
			int orderby = this.getParaToInt("priority");
			isSuccess = organizationService.changeOrganizationPriority(parentId,type,orderby);
		}catch(Exception e){
			isSuccess = false;
			log.error("修改机构显示顺序异常", e);
		}
		this.returnJsonResult(isSuccess);
	}
	
	//【异步】 逻辑删除组织机构 
	public void deleteOrganization(){
		boolean isSuccess = true;
		String message = null;
		try{
			Long orgId = this.getParaToLong("orgId");
			if(organizationService.deleteOrganizationCheck(orgId)){
				isSuccess = organizationService.deleteOrganization(orgId);
			}else{
				isSuccess = false;
				message = "删除失败！ 该组织机构存在关联子机构\\角色\\用户";
			}
		}catch(Exception e){
			isSuccess = false;
			log.error("删除机构异常", e);
		}
		this.returnJsonResult(isSuccess,message);
	}
}
